package com.app.service.impl;

import cn.hutool.core.date.DateTime;
import com.app.common.SubsidyApplicationStaticCommon;
import com.app.mapper.EnterpriseInformationMapper;
import com.app.mapper.PersonalInformationMapper;
import com.app.mapper.SubsidyApplicationDetailsMapper;
import com.app.mapper.SubsidyApplicationMapper;
import com.app.model.EnterpriseInformationModel;
import com.app.model.PersonalInformationModel;
import com.app.model.SubsidyApplicationDetailsModel;
import com.app.model.SubsidyApplicationModel;
import com.app.service.SubsidyApplicationDetailsService;
import com.app.util.IdCardCheckUtils;
import com.app.util.Result;
import com.app.vo.SADetailVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class SubsidyApplicationDetailsSereviceImpl extends ServiceImpl<SubsidyApplicationDetailsMapper, SubsidyApplicationDetailsModel> implements SubsidyApplicationDetailsService {
    @Autowired
    private IdCardCheckUtils idCardCheckUtils;
    @Autowired
    private SubsidyApplicationDetailsMapper subsidyApplicationDetailsMapper;
    @Autowired
    private PersonalInformationMapper personalInformationMapper;
    @Autowired
    private EnterpriseInformationMapper enterpriseInformationMapper;
    @Autowired
    private SubsidyApplicationMapper subsidyApplicationMapper;

    /**
     * 新增一条申请记录详情
     *
     * @param id
     * @param enterpriseInformationModel
     * @param personalInformationModel
     * @param subsidyApplicationId
     * @param subsidyApplicationDetailId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(Integer id,
                      EnterpriseInformationModel enterpriseInformationModel,
                      PersonalInformationModel personalInformationModel,
                      Integer subsidyApplicationId,
                      Integer subsidyApplicationDetailId) {

        if(!idCardCheckUtils.idCardNumberCheck(personalInformationModel.getIdCards())){
            return Result.error(400,"身份证号码格式错误");
        }
        //校验手机号
        if (personalInformationModel.getPhone() != null && !personalInformationModel.getPhone().equals("")) {
            String mobileNumber = personalInformationModel.getPhone();
            if (!validateMobileNumber(mobileNumber)) {
                return Result.error(400,"手机号格式错误");
            }
        }
        SubsidyApplicationDetailsModel subsidyApplicationDetailsModel = subsidyApplicationDetailsMapper.selectOne(new QueryWrapper<SubsidyApplicationDetailsModel>()
                .eq("subsidy_application_id", subsidyApplicationId));
        SubsidyApplicationModel subsidyApplicationModel = new SubsidyApplicationModel();
        if (subsidyApplicationDetailId == 0 && subsidyApplicationDetailsModel == null) {//新增
            //对应的企业信息
            enterpriseInformationModel.setState(SubsidyApplicationStaticCommon.REVIEW_OF_PERSONNEL_INFORMATION_WAIT);
            enterpriseInformationModel.setCrtTime(LocalDateTime.now());
            subsidyApplicationModel.setId(subsidyApplicationId);
            subsidyApplicationModel.setApplicationState(SubsidyApplicationStaticCommon.AWAITING_PARTY);
            //个人信息
            if (personalInformationModel.getId() == null) {//未提交过个人信息的
                personalInformationModel.setState(SubsidyApplicationStaticCommon.REVIEW_OF_PERSONNEL_INFORMATION_WAIT);
                personalInformationModel.setUserId(id);
                personalInformationModel.setCrtTime(LocalDateTime.now());
            }

            subsidyApplicationDetailsModel = new SubsidyApplicationDetailsModel();
            subsidyApplicationDetailsModel.setSubsidyState(SubsidyApplicationStaticCommon.REVIEWED_BY_THE_HUMAN_RESOURCES_AND_SOCIAL_SECURITY_BUREAU);
            subsidyApplicationDetailsModel.setCrtTime(LocalDateTime.now());
            subsidyApplicationDetailsModel.setSubsidyApplicationId(subsidyApplicationId);
        } else {//重新提交
            subsidyApplicationDetailsModel = subsidyApplicationDetailsMapper.selectById(subsidyApplicationDetailId);
            if (subsidyApplicationDetailsModel != null){
//                if (personalInformationModel.getResubmit() == 1) {//判断是否修改 1修改了
                    personalInformationModel.setId(subsidyApplicationDetailsModel.getPersonalInformationId());
                    personalInformationModel.setState(SubsidyApplicationStaticCommon.REVIEW_OF_PERSONNEL_INFORMATION_WAIT);
                    personalInformationModel.setReason("");
                    personalInformationModel.setUpTime(LocalDateTime.now());
//                }
//                if (enterpriseInformationModel.getResubmit() == 1) {
                    enterpriseInformationModel.setId(subsidyApplicationDetailsModel.getEnterpriseInformationId());
                    enterpriseInformationModel.setState(SubsidyApplicationStaticCommon.REVIEW_OF_PERSONNEL_INFORMATION_WAIT);
                    enterpriseInformationModel.setReason("");
                    enterpriseInformationModel.setUpTime(LocalDateTime.now());
//                }
                subsidyApplicationDetailsModel.setSubsidyState(SubsidyApplicationStaticCommon.REVIEWED_BY_THE_HUMAN_RESOURCES_AND_SOCIAL_SECURITY_BUREAU);
                subsidyApplicationDetailsModel.setReason("");
                subsidyApplicationDetailsModel.setUpTime(LocalDateTime.now());
            }
        }
//        try {
//            if (subsidyApplicationDetailId == 0) {//新增
//                personalInformationMapper.insert(personalInformationModel);
//                enterpriseInformationMapper.insert(enterpriseInformationModel);
//                subsidyApplicationDetailsModel.setPersonalInformationId(personalInformationModel.getId());
//                subsidyApplicationDetailsModel.setEnterpriseInformationId(enterpriseInformationModel.getId());
//                if (subsidyApplicationDetailsModel.getId() == null) {
//                    subsidyApplicationDetailsMapper.insert(subsidyApplicationDetailsModel);
//                } else {
//                    subsidyApplicationDetailsMapper.updateById(subsidyApplicationDetailsModel);
//                }
//            } else {//重新提交
//                if (enterpriseInformationModel.getResubmit() == 1) {
//                    enterpriseInformationMapper.updateById(enterpriseInformationModel);
//                }
//                if (personalInformationModel.getResubmit() == 1) {
//                    personalInformationMapper.updateById(personalInformationModel);
//                }
//                subsidyApplicationDetailsMapper.updateById(subsidyApplicationDetailsModel);
//            }
//        } catch (Exception e) {
//            log.error("新增申请详情提交失败,报错信息如下:" + e.getMessage());
//            return Result.error(500, "申请提交失败，请稍后重试");
//        }
        if (subsidyApplicationDetailId == 0) {//新增
            personalInformationMapper.insert(personalInformationModel);
            enterpriseInformationMapper.insert(enterpriseInformationModel);
            subsidyApplicationDetailsModel.setPersonalInformationId(personalInformationModel.getId());
            subsidyApplicationDetailsModel.setEnterpriseInformationId(enterpriseInformationModel.getId());
            subsidyApplicationMapper.updateById(subsidyApplicationModel);
            if (subsidyApplicationDetailsModel.getId() == null) {
                subsidyApplicationDetailsMapper.insert(subsidyApplicationDetailsModel);
            } else {
                subsidyApplicationDetailsMapper.updateById(subsidyApplicationDetailsModel);
            }
        } else {//重新提交
//            if (enterpriseInformationModel.getResubmit() == 1) {
                enterpriseInformationMapper.updateById(enterpriseInformationModel);
//            }
//            if (personalInformationModel.getResubmit() == 1) {
                personalInformationMapper.updateById(personalInformationModel);
//            }
            subsidyApplicationDetailsMapper.updateById(subsidyApplicationDetailsModel);
        }
        return Result.success("申请提交成功");
    }




    //校验手机号
    public boolean validateMobileNumber(String mobileNumber) {
        // 中国大陆手机号的正则表达式
        String regex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(mobileNumber);
        return matcher.matches();
    }

    /**
     * 根据申请表Id查询申请详情表 审核状态进度
     *
     * @param subsidyApplicationId
     * @return
     */
    @Override
    public Result getSAStatusBySAId(Integer subsidyApplicationId) {
        SubsidyApplicationDetailsModel subsidyApplication = subsidyApplicationDetailsMapper.selectOne(new QueryWrapper<SubsidyApplicationDetailsModel>()
                .eq("subsidy_application_id", subsidyApplicationId));

        Integer personalInformationId = subsidyApplication.getPersonalInformationId();
        Integer enterpriseInformationId = subsidyApplication.getEnterpriseInformationId();

        QueryWrapper<PersonalInformationModel> PersonalInformationModel = new QueryWrapper<>();
        PersonalInformationModel.eq("id", personalInformationId);
        PersonalInformationModel personalInformationModel = personalInformationMapper.selectOne(PersonalInformationModel);
        subsidyApplication.setPersonalInformationModel(personalInformationModel);

        QueryWrapper<EnterpriseInformationModel> enterpriseInformationModel = new QueryWrapper<>();
        enterpriseInformationModel.eq("id", enterpriseInformationId);
        EnterpriseInformationModel enterpriseInformationModel1 = enterpriseInformationMapper.selectOne(enterpriseInformationModel);
        subsidyApplication.setEnterpriseInformationModel(enterpriseInformationModel1);

        return Result.success(subsidyApplication);
    }

    /**
     * 小程序————重新审核时根据Id查询
     *
     * @param subsidyApplicationDetailId
     * @return
     */
    @Override
    public Result getDetailById(Integer subsidyApplicationDetailId) {
        SADetailVo saDetailVo = subsidyApplicationDetailsMapper.getDetailById(subsidyApplicationDetailId);
        return Result.success(saDetailVo);
    }
}
